<template>
    <div class="zy-content pb50">
        <back-level/>
        <template v-if="active">
            <component
                ref="component"
                v-for="(item,index) in componentsList"
                :key="index"
                :is="item.cKey"
                :disabled.sync="item.disabled"
                :info.sync="info"
                :approvalInfo="getCurrentApproval(info.flows,item.key)"
                :rejectFlows="getCurrentReject(info.rejectFlows,item.key)"
                :expand="item.expand"
                :components="item.components"
                :currentKey="active"
                :id="item.cKey"
                :class="{isOperation: (item.key!=='subProcess' && (active===item.key && active !=='Post Calculation') || (!active && item.key==='Spec. In'))}"
            >
            </component>
        </template>
        <projectProcess :info.sync="info" v-show="info.id"/>
        <jumpBindding :id="info.id" ref="jumpBidding"/>
        <rollbackModal ref="rollbackModal" :active="active" :id="info.id"/>
        <bottom-handle-wrap v-if="isEndProcess && info.displayButton!=1">
<!--            v-has="'capexCallback'"-->
            <Button  :loading="btnLoading" v-if="canRollback" @click="rollback">{{ $t('回退') }}</Button>
            <Button @click="$router.go(-1)">{{ $t('取消') }}</Button>
<!--            v-has="'capexJump'"-->
            <Button :loading="btnLoading" v-if="active==='Bidding'" @click="jumpBiddingMethod">{{ $t('跳过') }}</Button>
<!--            v-has="'capexCache'"-->
            <Button  :loading="btnLoading" style="margin-right: 10px" type="warn" v-if="showCacheBtn" @click="onCache">{{ $t('暂存') }}
            </Button>
<!--            //v-has="'capexSubmit'"-->
            <Button  :loading="btnLoading" style="margin-right: 10px" type="primary" @click="onSubmit">{{$t('提交')}}
            </Button>
        </bottom-handle-wrap>
    </div>
</template>

<script>
import specIn from "@/views/devBasic/capex/components/specIn";
// import specInApproval from "@/views/devBasic/capex/components/specInApproval";
import bdgApproval from "@/views/devBasic/capex/components/bdgApproval";
import bidding from "@/views/devBasic/capex/components/bidding";
// import biddingApproval from "@/views/devBasic/capex/components/biddingApproval";
import confirmVendor from "@/views/devBasic/capex/components/confirmVendor";
import confirmVendorApproval from "@/views/devBasic/capex/components/confirmVendorApproval";
import specOut from "@/views/devBasic/capex/components/specOut";
// import specOutApproval from "@/views/devBasic/capex/components/specOutApproval";
import contractSignOff from "@/views/devBasic/capex/components/contractSignOff";
// import contractSignOffApproval from "@/views/devBasic/capex/components/contractSignOffApproval";
import pr from "@/views/devBasic/capex/components/pr";
// import prApproval from "@/views/devBasic/capex/components/prApproval";
import downPayment from "@/views/devBasic/capex/components/downPayment";
import downPaymentApproval from "@/views/devBasic/capex/components/downPaymentApproval";
import sat from "@/views/devBasic/capex/components/sat";
import satApproval from "@/views/devBasic/capex/components/satApproval";
import cat from "@/views/devBasic/capex/components/cat";
import catApproval from "@/views/devBasic/capex/components/catApproval";
import fat from "@/views/devBasic/capex/components/fat";
import fatApproval from "@/views/devBasic/capex/components/fatApproval";
import capitalization from "@/views/devBasic/capex/components/capitalization";
import capitalizationApproval from "@/views/devBasic/capex/components/capitalizationApproval";
import postCalculation from "@/views/devBasic/capex/components/postCalculation";
// import postCalculationApproval from "@/views/devBasic/capex/components/postCalculationApproval";
import projectProcess from "@/views/devBasic/capex/components/projectProcess";
import subProcess from "@/views/devBasic/capex/components/subProcess";
import downPayment2 from "@/views/devBasic/capex/components/downPayment2";
import downPaymentApproval2 from "@/views/devBasic/capex/components/downPaymentApproval2";
import downPayment3 from "@/views/devBasic/capex/components/downPayment3";
import downPaymentApproval3 from "@/views/devBasic/capex/components/downPaymentApproval3";
import jumpBindding from "@/views/devBasic/capex/components/jumpBindding";
import mixins from "@/views/devBasic/capex/components/mixins";
import rollbackModal from "@/views/devBasic/capex/components/rollbackModal";


function getComponents() {
    return [
        {cKey: "specIn", key: "Spec. In", approval: 0},
        // {cKey: "specInApproval", key: "Spec. In Approval", approval: 1},
        {cKey: "bidding", key: "Bidding", approval: 0},
        // {cKey: "biddingApproval", key: "Bidding Approval", approval: 1},
        {cKey: "confirmVendor", key: "Confirm Vendor", approval: 0, processCode: "confirmVendor"},
        {cKey: "confirmVendorApproval", key: "Confirm Vendor Approval", approval: 1, processCode: "confirmVendor"},
        // {cKey: "bdgApproval", key: "BDG Approval", approval: 1},
        {cKey: "specOut", key: "Spec. Out", approval: 0},
        // {cKey: "specOutApproval", key: "Spec. Out Approval", approval: 1},
        {cKey: "contractSignOff", key: "Contract Sign-off", approval: 0},
        // {cKey: "contractSignOffApproval", key: "Contract Sign-off Approval", approval: 1},
        {cKey: "pr", key: "PR", approval: 0},
        // {cKey: "prApproval", key: "PR Approval", approval: 1},
        {cKey: "downPayment", key: "Down Payment", approval: 0, processCode: "downPayment"},
        {cKey: "downPaymentApproval", key: "Down Payment Approval", approval: 1, processCode: "downPayment"},
        {cKey: "sat", key: "SAT", approval: 0, processCode: "SAT"},
        {cKey: "satApproval", key: "SAT Approval", approval: 1, processCode: "SAT"},
        {cKey: "cat", key: "CAT", approval: 0, processCode: "CAT"},
        {cKey: "catApproval", key: "CAT Approval", approval: 1, processCode: "CAT"},
        {cKey: "downPayment2", key: "2nd Payment", approval: 0, processCode: "downPayment2"},
        {cKey: "downPaymentApproval2", key: "2nd Payment Approval", approval: 1, processCode: "downPayment2"},
        {cKey: "fat", key: "FAT", approval: 0, processCode: "FAT"},
        {cKey: "fatApproval", key: "FAT Approval", approval: 1, processCode: "FAT"},
        {cKey: "downPayment3", key: "3nd Payment", approval: 0, processCode: "downPayment3"},
        {cKey: "downPaymentApproval3", key: "3nd Payment Approval", approval: 1, processCode: "downPayment3"},
        {cKey: "capitalization", key: "Capitalization", approval: 0, processCode: "Capitalization"},
        {cKey: "capitalizationApproval", key: "Capitalization Approval", approval: 1, processCode: "Capitalization"},
        {cKey: "postCalculation", key: "Post Calculation", approval: 0},
        // {cKey: "postCalculationApproval", key: "Post Calculation Approval", approval: 1},
    ]
}


export default {
    name: "operation",
    components: {
        specIn,
        // specInApproval,
        // bdgApproval,
        bidding,
        // biddingApproval,
        confirmVendor,
        confirmVendorApproval,
        specOut,
        // specOutApproval,
        contractSignOff,
        // contractSignOffApproval,
        pr,
        // prApproval,
        downPayment,
        downPaymentApproval,
        sat,
        satApproval,
        cat,
        catApproval,
        fat,
        fatApproval,
        capitalization,
        capitalizationApproval,
        postCalculation,
        // postCalculationApproval,
        projectProcess,
        subProcess,
        downPaymentApproval2,
        downPayment2,
        downPaymentApproval3,
        downPayment3,
        jumpBindding,
        rollbackModal
    },
    mixins: [mixins],
    data() {
        return {
            active: "",
            approval: '',
            componentsList: [],
            refIndex: "",
            info: {
                orderProcessStatus: 0,
                flows: [],
                biddingIsRequired: 1,
                twoPaymentBeforeCat: 0,
                displayButton: 0
            },
            isEnd: false,
            btnLoading: false,
            canRollback: false,
            iframeShow: false,
            iframeModalSrc: "",
            printObj: {},
            showCacheBtn: false
        }
    },
    computed: {
        isEndProcess: function () {
            let status = false
            if (this.$route.query.mainIdTag != 1) {
                if (this.info.orderProcessStatus == 0) status = true
            } else {
                if (["Confirm Vendor Approval"].includes(this.info.progressCode) && this.info.finishFlag == 0) {
                    status = true
                } else {
                    status = false
                }
                if (!this.info.progressCode || ["Spec. In","Bidding","Confirm Vendor"].includes(this.info.progressCode)) {
                    status = true
                }
            }
            return status
        }
    },
    mounted() {
        if (this.$route.query.type === 'add') {
            const components = getComponents();
            this.active = 'Spec. In'
            this.approval = 0
            this.componentsList = [components[0]]
            this.refIndex = 0
        } else {
            this.getInfo()
        }
    },
    methods: {
        rollback() {
            this.$refs.rollbackModal.showModal()
        },
        getCurrentApproval(list, code) {
            if (!(Array.isArray(list) && list.length > 0)) return {}
            return list.find(item => item.progressCode == code) || {}
        },
        getCacheBtn(active, list) {
            const obj = list.find(item => item.key === active);
            if (obj.approval == 0 && active !== '' && !(this.active === 'Confirm Vendor' && (this.info.cvRepeatTagging == 1 || this.info.cvRepeatTagging == 2))) {
                this.showCacheBtn = true
            }
        },
        getCurrentComponent(code) {

            let list = this.getProcessLayoutList(getComponents(), this.info)
            if (!this.info.progressCode) {
                list = list.splice(0, 1)
                list[list.length - 1]['disabled'] = false
                this.info.reSetSpecIn = 1
            }

            this.refIndex = (list.length - 1) / 1

            if (list.length - 2 >= 0)
                if (list[list.length - 2]['approval'] == 0 && list[list.length - 1]['approval'] == 0) {
                    this.canRollback = true
                }

            const cvStatus = this.info.progressCode === 'Confirm Vendor' && (this.info.cvRepeatTagging == 2 || this.info.cvRepeatTagging == 1)

            this.componentsList = list;
            this.approval = list[list.length - 1]['approval']
            this.active = list[list.length - 1]['key']

            if (cvStatus) {
                list[list.length - 1]['disabled'] = true
                list[list.length - 1]['expand'] = true
                list[list.length - 2]['disabled'] = false
                this.canRollback = false
                this.refIndex--
                this.approval = list[list.length - 2]['approval']
                this.active = list[list.length - 2]['key']

            }


            if (this.approval == 1 && list[list.length - 1]['processCode'] === list[list.length - 2]['processCode']) {
                list[list.length - 2]['expand'] = true
            }

            if (this.info.progressCode === "Post Calculation") {
                this.isEnd = true
            }

            this.$store.commit('capexProcessSchedule', {
                active: this.active,
                flows: this.info.flows,
                isEnd: this.isEnd,
                biddingIsRequired: this.info.biddingIsRequired,
                satIsRequired: this.info.satIsRequired,
                twoPaymentBeforeCat: this.info.twoPaymentBeforeCat,
                render: true,
                mainId: this.info.id
            })

            this.getCacheBtn(this.active, list)


            this.$forceUpdate()
        },
        getSubCurrentComponent() {

            let components = getComponents()


            let _list = this.getProcessLayoutList(components, this.info)

            let list = _list.slice(0, 4)



            // if (this.info.rejectBidding ==0){
            //     _list = [_list[0]]
            // }else{
                if (["Confirm Vendor Approval"].includes(this.info.progressCode) || this.info.orderProcessStatus === 1) {
                    list.push({cKey: "subProcess", key: "subProcess", approval: 1, components: []})
                }
            // }


            if (this.info.finishFlag === 0) {
                const obj = components.splice(components.length - 1, 1)[0]
                if (this.info.orderProcessStatus === 1) {
                    obj.disabled = true
                }
                list.push(obj)
            }

            /**
             * bidding驳回到 Spec. In
             */

            if (!this.info.progressCode) {
                list = [list[0]]
                list[0].disabled = false
                this.info.reSetSpecIn = 1
            }
            this.refIndex = list.length - 1
            this.active = list[list.length - 1]['key']
            this.approval = list[list.length - 1]['approval']

            if (list.length - 2 >= 0)
                if (list[list.length - 2]['approval'] == 0 && list[list.length - 1]['approval'] == 0) {
                    this.canRollback = true
                }
            const cvStatus = this.info.progressCode === 'Confirm Vendor' && (this.info.cvRepeatTagging == 2 || this.info.cvRepeatTagging == 1)
            if (cvStatus) {
                list[list.length - 1]['disabled'] = true
                list[list.length - 1]['expand'] = true
                list[list.length - 2]['disabled'] = false
                this.canRollback = false
                this.refIndex--
                this.approval = list[list.length - 2]['approval']
                this.active = list[list.length - 2]['key']

            }

            if (this.approval == 1 && list[list.length - 1]['processCode'] === list[list.length - 2]['processCode']) {
                list[list.length - 2]['expand'] = true
            }

            if (this.info.progressCode === "Post Calculation") {
                this.isEnd = true
            }

            this.$store.commit('capexProcessSchedule', {
                active: this.active,
                mainFlows: this.info.flows,
                flows: this.info.flows,
                isEnd: this.isEnd,
                progressCode: this.info.progressCode,
                mainId: this.info.id,
                render:["Spec. In","Bidding","Confirm Vendor"].includes(this.info.progressCode) || !this.info.progressCode,
                // biddingIsRequired: this.info.biddingIsRequired,
                // satIsRequired: this.info.satIsRequired,
                // twoPaymentBeforeCat: this.info.twoPaymentBeforeCat,
            })

            this.getCacheBtn(this.active, list)
            this.componentsList = list

        },
        getInfo() {
            if (this.$route.query.mainIdTag == 1) {
                this.axios({
                    method: 'get',
                    url: '/dms/capex/findByMainId',
                    params: {id: this.$route.query.id}
                }).then(res => {
                    if (res.code === 200) {
                        // this.info = res.data;
                        let data = res.data
                        const cacheInfo = this.getCacheData(data)
                        data = {...data, ...cacheInfo}
                        const {capexSubmitPos} = data;
                        this.info = data;

                        const {
                            bdgAmoutCount,
                            downPaymentAmoutCount,
                            towPaymentAmoutCount,
                            thirdPaymentAmoutCount,
                            companyName,
                            projectId,
                            orgId,
                            rejectBidding
                        } = this.info;

                        this.info = Object.assign(this.info, {
                            bdgAmoutCount,
                            downPaymentDto1: {dpAmount: downPaymentAmoutCount},
                            downPaymentDto2: {dpAmount: towPaymentAmoutCount},
                            downPaymentDto3: {dpAmount: thirdPaymentAmoutCount},
                            source: "child",
                            companyName,
                            mainProjectId: projectId,
                            mainOrgId: orgId
                        })

                        if (rejectBidding==1){
                            this.info.progressCode = ''
                        }

                        this.getSubCurrentComponent(capexSubmitPos)

                    } else {
                        this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                    }
                })
            } else {
                this.axios({
                    method: 'get',
                    url: '/dms/capex/findById',
                    params: {id: this.$route.query.id}
                }).then(res => {
                    if (res.code === 200) {
                        let data = res.data
                        const cacheInfo = this.getCacheData(data)
                        data = {...data, ...cacheInfo}
                        this.info = data;
                        this.info.mainCompanyName = this.info.companyName
                        this.info.mainOrgId = this.info.orgId

                        const {progressCode, progressStatus} = this.info;

                        this.getCurrentComponent(progressCode, progressStatus)

                    } else {
                        this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                    }
                })
            }

        },
        async onSubmit() {


            const params = await this.$refs.component[this.refIndex].getParams()

            if (!params) return;


            params.progressCode = this.active
            params.id = this.$route.query.id
            delete params.projectOwner
            delete params.submitByStr

            this.btnLoading = true
            if (this.approval == 1) {
                this.axios({
                    method: 'post',
                    url: '/dms/capex/approval',
                    data: params
                }).then(res => {
                    if (res.code === 200) {
                        this.$Message.success(res.msg)
                        this.$router.go(-1)
                    } else {
                        this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                    }
                }).finally(() => {
                    this.btnLoading = false
                })
            } else {
                this.axios({
                    method: 'post',
                    url: '/dms/capex/submit',
                    data: params
                }).then(res => {
                    if (res.code === 200) {
                        this.$Message.success(res.msg)
                        this.$router.go(-1)
                    } else {
                        this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                    }
                }).finally(() => {
                    this.btnLoading = false
                })
            }
        },
        jumpBiddingMethod() {
            this.$refs.jumpBidding.show()
        },
        async onCache() {

            const params = await this.$refs.component[this.refIndex].getParams(true)

            if (!params) return;
            params.progressCode = this.active
            params.id = this.$route.query.id
            delete params.projectOwner
            delete params.submitByStr
            delete params.preparedByName

            if (params.cvInfo) {
                delete params.cvInfo.requestedBy
                delete params.cvInfo.submitByStr
            }

            if (params.scfInfoDto) {
                delete params.scfInfoDto.submitByStr
            }

            if (params.downPaymentDto) {
                delete params.downPaymentDto.submitByStr
                delete params.downPaymentDto.preparedByName
                delete params.downPaymentDto.applyByName
            }

            if (params.capexCapitalizationInfoDTO) {
                delete params.capexCapitalizationInfoDTO.submitByStr
            }


            this.btnLoading = true

            this.axios({
                method: 'post',
                url: '/dms/capex/cachePONodeInfo',
                data: params
            }).then(res => {
                if (res.code === 200) {
                    this.$Message.success(res.msg)

                    // this.$router.go(-1)
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            }).finally(() => {
                this.btnLoading = false
            })
        }
    }
}
</script>
<style lang="scss">
#app .detail-content-layout {
    &.isOperation {
        border: rgba(3, 91, 236, 1) solid 1px;

        .ivu-card-head {
            background: rgba(3, 91, 236, 0.1);
        }
    }
}

#app .isOperation {
    .detail-content-layout {
        border: rgba(3, 91, 236, 1) solid 1px;

        .ivu-card-head {
            background: rgba(3, 91, 236, 0.1);
        }
    }
}
</style>
